package com.fyl.datasource.aop;

import com.fyl.datasource.anno.TargetDataSource;
import com.fyl.datasource.context.DataSourceContextHolder;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.springframework.core.annotation.AnnotationUtils;

import java.lang.reflect.Method;

public class TargetDataSourceAnnotationMethodInterceptor implements MethodInterceptor {

    private static final TargetDataSourceClassResolver RESOLVER = new TargetDataSourceClassResolver();

    @Override
    public Object invoke(MethodInvocation methodInvocation) throws Throwable {
        try {
            DataSourceContextHolder.putDataSourceKey(determineDatasource(methodInvocation));
            return methodInvocation.proceed();
        } finally {
            DataSourceContextHolder.clearDataSourceKey();
        }
    }

    private String determineDatasource(MethodInvocation invocation) throws Throwable {
        Method method = invocation.getMethod();
        TargetDataSource anno = method.isAnnotationPresent(TargetDataSource.class)
                ? method.getAnnotation(TargetDataSource.class)
                // 找到 mapperProxy 代理的 mapper 接口上的注解 TargetDataSource
                : AnnotationUtils.findAnnotation(RESOLVER.targetClass(invocation), TargetDataSource.class);
        return anno.value();
    }
}
